//
//
//  Created by xudexin on 13-4-17.
//
//

#ifndef __Pomelo__
#define __Pomelo__

#include "cocos2d.h"

#include "jansson.h"
#include "pomelo.h"
#include<queue>
//#include <pthread.h>

//using namespace cocos2d;
USING_NS_CC;

#define PLAYERUID "20000"
class PomeloContent_;
class PomeloReponse_;
class PomeloEvent_ ;
class PomeloNotify_;
class PomeloConnect_;

class PomeloReponse:public cocos2d::Ref{
public:
    PomeloReponse(){}
    ~PomeloReponse(){}
    const char* rout;
    int status;
    json_t *docs;
};

class Pomelo :public cocos2d::Ref{
public:
    static Pomelo *getInstance();
    static void destroyInstance();
    
    
    int connect(const char* addr,int port);
    
    void asyncConnect(const char* addr,int port,Ref* pTarget, SEL_CallFuncND pSelector);

    void stop();

    int request(const char*route,json_t *msg,Ref* pTarget, SEL_CallFuncND pSelector);
    int notify(const char*route,json_t *msg,Ref* pTarget, SEL_CallFuncND pSelector);
    int addListener(const char* event,Ref* pTarget, SEL_CallFuncND pSelector);
    void removeListener(const char* event);

public:
    Pomelo();
    virtual ~Pomelo();
    
    void cleanup();
    
    void cleanupEventContent();
    void cleanupNotifyContent();
    void cleanupRequestContent();
    
    void dispatchCallbacks(float delta);
    
    
    void lockReponsQeueue();
    void unlockReponsQeueue();
    void lockEventQeueue();
    void unlockEventQeueue();
    void lockNotifyQeueue();
    void unlockNotifyQeueue();
    
    void lockConnectContent();
    void unlockConnectContent();
    
    
    void pushReponse(PomeloReponse_*resp);
    void pushEvent(PomeloEvent_*ev);
    void pushNotiyf(PomeloNotify_*ntf);
    void connectCallBack(int status);

private:
    void incTaskCount();
    void desTaskCount();
    
    PomeloReponse_*popReponse();
    PomeloEvent_*popEvent();
    PomeloNotify_*popNotify();
    
    std::map<pc_notify_t*,PomeloContent_*> notify_content;
   // pthread_mutex_t  notify_queue_mutex;
    std::queue<PomeloNotify_*> notify_queue;
    
    std::map<std::string,PomeloContent_*> event_content;
   // pthread_mutex_t  event_queue_mutex;
    std::queue<PomeloEvent_*> event_queue;
    
    std::map<pc_request_t *,PomeloContent_*> request_content;
   // pthread_mutex_t  reponse_queue_mutex;
    std::queue<PomeloReponse_*> reponse_queue;
    
    
   // pthread_mutex_t  connect_mutex;
    PomeloConnect_* connect_content;
    
    
   // pthread_mutex_t  task_count_mutex;
    void dispatchRequest();
    void dispatchEvent();
    void dispatchNotify();
    void connectCallBack();
    pc_client_t *client;
    int task_count;
    int connect_status;
};

#endif /* defined(__Pomelo__) */